﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Accord.Audio;
using Accord.Audio.Formats;
using Accord.Audio.Windows;
using AForge.Math;

namespace TimbreRecognition
{
    public class MFCCAdapter
    {
        private static int MEL_BANDS = 30;

        private int numberOfCoefficients;

        public MFCCAdapter(int numberOfCoefficients)
        {
            this.numberOfCoefficients = numberOfCoefficients;
        }

        public double[] Compute(Signal signal)
        {
            IWindow window = RaisedCosineWindow.Hamming(signal.Length);
            window.Apply(signal, 0);

            ComplexSignal cs = ComplexSignal.FromSignal(signal);
            cs.ForwardFourierTransform();
  
            Complex[] complex = cs.GetChannel(0);

            double[] fftBufferR = new double[complex.Length];
            double[] fftBufferI = new double[complex.Length];

            // Convert audio buffer to doubles
            for (int i = 0; i < complex.Length; i++)
            {
                Complex c = complex[i];
                fftBufferR[i] = c.Re;
                fftBufferI[i] = c.Im;
            }

            MFCC featureMFCC = new MFCC(complex.Length, numberOfCoefficients, MEL_BANDS, signal.SampleRate);
            double[] featureCepstrum = featureMFCC.cepstrum(fftBufferR, fftBufferI);

            return featureCepstrum;
        }

        

        //public double[] Compute(int[] data, int sampleRate)
        //{
        //    MFCC featureMFCC = new MFCC(data.Length, MFCCS_VALUE, MEL_BANDS, sampleRate);

        //    FFT featureFFT = new FFT(data.Length);
        //    //int windowSize = Math.Min(sampleRate, data.Length);
        //    //window = new Window(windowSize); 

        //    double[] fftBufferR = new double[data.Length];
        //    double[] fftBufferI = new double[data.Length];
               
        //    // Convert audio buffer to doubles
        //    for (int i = 0; i < data.Length; i++)
        //    {
        //        fftBufferR[i] = data[i];
        //    }

        //    // In-place windowing
        //  //   window.applyWindow(fftBufferR);

        //    // In-place FFT
        //    featureFFT.fft(fftBufferR, fftBufferI);

        //    // Get MFCCs
        //    double[]  featureCepstrum = featureMFCC.cepstrum(fftBufferR, fftBufferI);

        //    return featureCepstrum;    
        //}
    }
}
